use std::ops::Deref;
use std::vec::Vec;


#[derive(Debug, Clone)]
pub struct CallbackFunc<T> {
    func: fn(T),
}
impl<T> CallbackFunc<T> {
    pub fn new(call: fn(T)) -> Self {
        CallbackFunc { func: call }
    }
    pub fn on_event(&self, obj: T) {
        (self.func)(obj);
    }
}

// 定义回调 trait
pub trait Callback: Fn() + 'static {}
impl<F: Fn() + 'static> Callback for F {}

pub struct CallbackStorage {
    callbacks: Vec<Box<dyn Callback>>,
}

impl CallbackStorage {
    pub fn new() -> Self {
        CallbackStorage {
            callbacks: Vec::new(),
        }
    }

    // 注册回调
    pub fn register<F: Callback>(&mut self, callback: F) {
        self.callbacks.push(Box::new(callback));
    }

    // 触发所有回调
    pub fn trigger_all(&self) {
        for callback in &self.callbacks {
            callback();
        }
    }
}

fn test2() {
    let mut storage = CallbackStorage::new();

    // 注册第一个回调
    storage.register(|| {
        println!("这是第一个回调");
    });

    // 注册第二个回调
    let name = String::from("Rust");
    storage.register(move || {
        println!("这是第二个回调，来自 {}", name);
    });

    // 触发所有回调
    storage.trigger_all();
}
// pub trait Callback: Fn() + 'static {}
// impl<F: Fn() + 'static> Callback for F {}
pub struct CallbackHandler<T> {
    callback: Box<dyn Fn(T)>,
}

impl<T> CallbackHandler<T> {
    pub fn new<F>(callback: F) -> Self
    where
        F: Fn(T) + 'static,
    {
        CallbackHandler {
            callback: Box::new(callback),
        }
    }

    pub fn trigger(&self, value: T) {
        (self.callback)(value);
    }
}
fn test5() {
    let prefix = String::from("收到值:");

    let handler = CallbackHandler::new(move |value| {
        println!("{} {}", prefix, value);
    });

    handler.trigger(100);
    handler.trigger(200);
}
